package com.qk.aspect;

import com.qk.entity.OperateLog;
import com.qk.mapper.OperateLogMapper;
import com.qk.utils.CurrentUserHoler;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
/**
 * 记录日志
 */
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(com.qk.anno.Log)")
    public Object log(ProceedingJoinPoint pjp) throws Throwable {

        OperateLog operateLog = new OperateLog();
        operateLog.setOperateUserId(CurrentUserHoler.getCurrentUser());// 操作用户
        operateLog.setOperateTime(LocalDateTime.now());// 操作时间
        operateLog.setClassName(pjp.getTarget().getClass().getName());//类名
        operateLog.setMethodName(pjp.getSignature().getName());//方法名
        operateLog.setMethodParams(Arrays.toString(pjp.getArgs()));//传入参数

        long start = System.currentTimeMillis();//开始运行 时间

        Object result = pjp.proceed();

        long end = System.currentTimeMillis();//结束运行 时间

        operateLog.setReturnValue(result.toString());//返回值
        operateLog.setCostTime(end - start);//耗时
        operateLogMapper.insert(operateLog);//插入数据库
        return result;
    }
}
